#!/bin/bash
#自动发现注册java服务名称和对应端口

#S_NAME1='tomcat'
#S_NAME2='resin'
S_NAME1=$1
S_NAME2=$2

serv_info=($(netstat -ntlp|egrep -v '005|009|6600'|awk -F'[:/ ]+' '/java/{print $5,$9}'))
length=${#serv_info[@]}

printf "{\n"
printf  '\t'"\"data\":["
for ((i=0;i<$length;i+=2))
do
    tcp_port=${serv_info[$i]}
    pid_no=${serv_info[$i+1]}
    pid_comm=`ps $pid_no|grep -v TTY`
    if [[ "$pid_comm" =~ "$S_NAME1" ]];
    then
        ser_name=$S_NAME1
    fi
    if [[ "$pid_comm" =~ "$S_NAME2" ]];
    then
        ser_name=$S_NAME2
    fi
    printf '\n\t\t{'
    printf "\"{#SRV_PORT}\":\"$tcp_port\",\"{#SRV_NAME}\":\"$ser_name\"}"
    if [ $i -lt $[$length-2] ];then
        printf ','
    fi
done
printf  "\n\t]\n"
printf "}\n"
